package com.zhanghu.backendZray.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhanghu.backendZray.cache.ContextCache;
import com.zhanghu.backendZray.converter.FileConverter;
import com.zhanghu.backendZray.pojo.entity.File;
import com.zhanghu.backendZray.mapper.FileMapper;
import com.zhanghu.backendZray.pojo.request.file.FilePageRequest;
import com.zhanghu.backendZray.pojo.vo.FileVo;
import com.zhanghu.backendZray.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author zhangdong
 * @since 2024-08-17
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {
    private final FileConverter fileConverter;

    /**
     * 分页查询
     * @param request
     * @return
     */
    @Override
    public Page<FileVo> page(FilePageRequest request) {
        Page<File> pageQuery = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<File>()
                .in(CollUtil.isNotEmpty(request.getIdList()), File::getId, request.getIdList())
                .eq(File::getUserId, ContextCache.currentUserId())
                .like(StrUtil.isNotEmpty(request.getName()), File::getName, request.getName())
                .orderByDesc(File::getId);
        if (request.getStartDate() != null) {
            queryWrapper.between(File::getCreateTime,
                    LocalDateTime.of(request.getStartDate(), LocalTime.of(0, 0, 0)),
                    LocalDateTime.of(request.getEndDate(), LocalTime.of(23, 59, 59)));
        }
        Page<File> page = baseMapper.selectPage(pageQuery, queryWrapper);
        List<File> list = page.getRecords();
        List<FileVo> userVos = fileConverter.entity2Vos(list);
        Page<FileVo> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(userVos);
        return resultPage;
    }

    public List<FileVo> listByIds(List<Integer> idList) {
        if (CollUtil.isEmpty(idList)) {
            return Collections.emptyList();
        }
        List<File> list = baseMapper.selectBatchIds(idList);
        List<FileVo> result = fileConverter.entity2Vos(list);
        return result;
    }
}
